package avicit.bdp.dgs.metadata.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.dgs.metadata.dao.MetadataModelDao;
import avicit.bdp.dgs.metadata.dto.MetadataModelDTO;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryRespBean;
import com.github.pagehelper.Page;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author mayi 元模型服务层
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MetadataModelService extends BaseService<MetadataModelDao, MetadataModelDTO> {

  @Resource private MetadataModelDao metadataModelDao;

  @Resource private ConvertColumnClient convertColumnClient;

  @Transactional(readOnly = true)
  public QueryRespBean<MetadataModelDTO> getPageList(
      String applyDatasourceType, String keyWords, Integer pageNo, Integer pageSize)
      throws Exception {

    QueryRespBean<MetadataModelDTO> queryRespBean = new QueryRespBean<>();
    com.github.pagehelper.PageHelper.startPage(pageNo, pageSize);
    Page<MetadataModelDTO> page = metadataModelDao.getPageList(applyDatasourceType, keyWords);
    queryRespBean.setResult(page);
    valueConvert(page.getResult());
    BdpLogUtil.log4Query(queryRespBean);
    return queryRespBean;
  }

  public String save(MetadataModelDTO dto) {
    if (StringUtils.isNotEmpty(dto.getApplyDatasourceType())) {
      MetadataModelDTO example = new MetadataModelDTO();
      example.setApplyDatasourceType(dto.getApplyDatasourceType());
      MetadataModelDTO existDto = this.mapper.selectOne(example);
      if (existDto != null) {
        dto.setId(existDto.getId());
        dto.setCreatedBy(existDto.getCreatedBy());
        dto.setCreationDate(existDto.getCreationDate());
        dto.setCreatedDept(existDto.getCreatedDept());
        updateByPrimaryKey(dto);
      } else {
        dto.setId(ComUtil.getId());
        dto.setStatus(Constants.STATUS_ZERO);
        dto.setVersion(1L);

        this.insertWithoutVersion(dto);
        log4Insert(dto);
      }
    } else {
      dto.setId(ComUtil.getId());
      dto.setVersion(1L);

      this.insertWithoutVersion(dto);
      log4Insert(dto);
    }

    return dto.getId();
  }

  public Boolean batchDelete(String ids) {
    CheckParaUtils.checkStringValidity(ids, logger, "没有传入待删除的ID");
    String[] idArr = ids.split(Constants.COMMA);
    for (String id : idArr) {
      MetadataModelDTO metadataModelDTO = this.selectByPrimaryKey(id);
      CheckParaUtils.checkDbObjectValidity(
          metadataModelDTO, logger, String.format("没有查到数据，请确保id:%s的数据是否存在", id));

      this.mapper.deleteByPrimaryKey(id);
      // 记录日志
      BdpLogUtil.log4Delete(metadataModelDTO);
    }
    return true;
  }

  public MetadataModelDTO queryById(String id) {
    MetadataModelDTO metadataModelDTO = this.selectByPrimaryKey(id);
    CheckParaUtils.checkDbObjectValidity(
        metadataModelDTO, logger, String.format("没有查到数据，请确保id:%s的数据是否存在", id));
    return metadataModelDTO;
  }

  public Boolean changeStatus(String id, Integer status) {
    MetadataModelDTO metadataModelDTO = queryById(id);
    metadataModelDTO.setStatus(status);

    String logTitle = "";
    if (status == 0) {
      logTitle = "停用元模型：【";
    } else {
      logTitle = "启用元模型：【";
    }
    logTitle += metadataModelDTO.getMetadataModelName() + "】";
    BdpLogUtil.log("元模型模块", logTitle, PlatformConstant.OpType.update);
    return this.updateByPrimaryKey(metadataModelDTO) > 0;
  }

  public List<String> getDataSourceTypeList(Integer status) {
    return metadataModelDao.getDataSourceTypeList(status);
  }

  public MetadataModelDTO queryByType(String dataSourceType) {
    return metadataModelDao.queryByType(dataSourceType);
  }

  /**
   * 添加系统参数
   *
   * @param dtoList
   */
  private void valueConvert(List<MetadataModelDTO> dtoList) {
    // 循环组装请求数据
    Map<String, Set<String>> convertFormData = new HashMap<>();
    if (CollectionUtils.isNotEmpty(dtoList)) {
      for (MetadataModelDTO dto : dtoList) {
        BusinessUtil.createConvertSet(convertFormData, avicit.bdp.core.constant.Constants.BDP_DATA_SECRET_LEVEL_KEY, dto.getSecretLevel());
      }

      if (convertFormData.size() > 0) {
        // 获取请求结果
        Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
        for (MetadataModelDTO dto : dtoList) {
          dto.setSecretLevelName(BusinessUtil.convertFormat(convertResultData, avicit.bdp.core.constant.Constants.BDP_DATA_SECRET_LEVEL_KEY, dto.getSecretLevel()));
        }
      }
    }
  }
}
